// 数据变化 => 视图更新

let oldArrayPrototype = Array.prototype
let proto = Object.create(oldArrayPrototype)
Array.from(['push', 'shift', 'unshift', 'pop']).forEach(method => {
  proto[method] = function () {
    updateView()
    oldArrayPrototype[method].call(this, ...arguments)
  }
});


function observer(target) {
  // 观察者
  if (typeof target !== 'object' || target == null) {
    // 非对象
    return target
  }
  if (Array.isArray(target)) {
    // 重写数组的原型
    target.__proto__ = proto
    return 
  }
  for (let key in target) {
    defineReactive(target, key, target[key])
  }
}

function defineReactive(target, key, value) {
  if (typeof value === 'object' && value !== null) {
    observer(value)
  }
  Object.defineProperty(target, key, {
    get() {
      return value
    },
    set(newVal) {
      if (newVal != value) {
        value = newVal
        updateView()
      }
    }
  })
}

function updateView() {
  console.log('视图更新');

}


let data = {
  name: 'Lionel',
  age: {
    num: 18,
    text: {
      a: '1',
      b: '2'
    }
  },
  list: [1, 2, 3, 4]
}

observer(data)
data.list.push(100)
console.log(data.list);

